package cn.liwq.demo.config;

import cn.liwq.demo.serializer.BigDecimalToStringSerializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.math.BigDecimal;

/**
 * @author lweiqiang
 * @date 2023/2/26
 */
@Configuration
public class JacksonConfiguration {
  @Bean
  @Primary
  ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper mapper = builder.createXmlMapper(false).build();
    AnnotationIntrospector primary = mapper.getSerializationConfig().getAnnotationIntrospector();
    AnnotationIntrospector annotationIntrospector =
        AnnotationIntrospectorPair.pair(primary, new ScaleFormatterAnnotationIntrospector());
    mapper.setAnnotationIntrospector(annotationIntrospector);
    // mapper.enable();
    // BigDecimal转字符串
    mapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
    // mapper.getFactory().getFactory
    return mapper;
  }

  /** 自定义序列化类型转换 */
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    Jackson2ObjectMapperBuilderCustomizer customizer =
        jacksonObjectMapperBuilder ->
            jacksonObjectMapperBuilder.serializerByType(
                BigDecimal.class, BigDecimalToStringSerializer.INSTANCE);
    return customizer;
  }
}
